using System;
using System.Collections.Specialized;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;

namespace BilSimser.SharePoint.Common.Controls
{
	public abstract class OWSBase : OWSControl, IPostBackDataHandler
	{
		/// <summary>
		/// Displayed information (possibly not used)
		/// </summary>
		public string Display
		{
			get { return "" + ViewState["Display"]; }
			set { ViewState["Display"] = value; }
		}

		/// <summary>
		/// Gets or the display text of the item.
		/// </summary>
		public virtual string Text
		{
			get { return Value; }
			set
			{ /* Do Nothing */
			}
		}

		/// <summary>
		/// The value of the text control
		/// </summary>
		public virtual string Value
		{
			get { return "" + ViewState["Value"]; }
			set { ViewState["Value"] = value; }
		}

		/// <summary>
		/// Indicates whether or not the control is a required field. 
		/// </summary>
		public bool Required
		{
			get
			{
				if (ViewState["Required"] == null)
					Required = false;
				return (bool) ViewState["Required"];
			}
			set { ViewState["Required"] = value; }
		}

		#region IPostBackDataHandler Members

		/// <summary>
		/// Gets the posted back data.
		/// </summary>
		/// <param name="postDataKey">data key for this control</param>
		/// <param name="postCollection">collection information</param>
		/// <returns>true if to fire event</returns>
		public virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
		{
			string present = Value;
			Value = postCollection[postDataKey];
			return (present != Value);
		}

		/// <summary>
		/// Raises the text changed event
		/// </summary>
		public virtual void RaisePostDataChangedEvent()
		{
			OnValueChanged(EventArgs.Empty);
		}

		/// <summary>
		/// Helper to raise the value changed event
		/// </summary>
		/// <param name="e">value</param>
		private void OnValueChanged (EventArgs e)
		{
			if (ValueChanged != null)
				ValueChanged(this, e);
		}

		/// <summary>
		/// fires when the value changes after a postback. 
		/// </summary>
		public event EventHandler ValueChanged;

		#endregion

		#region Helper Properties

		/// <summary>
		/// Formats the string for javascripting.
		/// </summary>
		protected string JavaScriptValue
		{
			get
			{
				return Value
					.Replace(@"\", @"\\")
					.Replace("\"", "\\\"")
					.Replace("'", "\'")
					.Replace("\r", "")
					.Replace("\n", "\\n");
				;
			}
		}

		#endregion
	}
}